<template>
  <div class="header" :style="'height:' + realheight + 'px;width:'+ sumWidth + 'px;'">
    <div class="gridbox">
      <div class="xhdr">
        <img src="/static/images/sort_desc.gif" style="display: none; position: absolute;">
        <table cellpadding="0" cellspacing="0" class="hdr">
          <tbody>
          <tr style="height: 0px;">
            <th style="width: 40px;" v-if="showCheckbox"></th>
            <th v-for="(val,i) in gridFullWidthInfo" :key="i" :style="'width:' + val + 'px;'"/>
          </tr>
          <tr class="hdrtr">
            <td class="hdrtd" style="cursor: default;" v-if="showCheckbox">
              <div class="hdrcell">
                <input type="checkbox" v-model="sumModel" value="0">
              </div>
            </td>
            <td v-for="(val,i) in gridTitleInfo"
                :key="i"
                class="hdrtd">
              <div class="hdrcell">{{val}}</div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <div class="objbox">
        <table cellpadding="0" cellspacing="0" style="width: 100%; table-layout: fixed;">
          <tbody>
          <tr style="height: 0px;">
            <!--1st th is for the checkbox-->
            <th style="width: 40px;" v-if="showCheckbox"></th>
            <th v-for="(val,i) in gridFullWidthInfo" :key="i" :style="'width:' + val + 'px;'"/>
          </tr>
          <tr v-for="(val,i) in gridInfo"
              :key="i"
              :class="className(i)">
            <td class="hdrcell2" title="" v-if="showCheckbox">
              <input type="checkbox" v-model="subModel" :value="i">
            </td>
            <td v-for="(val2,j) in gridShowInfo"
                :key="j"
                :title="val[val2]"
                @click="cellSelect(i,j,val,val2)"
                @dblclick="cellDoubleSelect(i,j,val,val2)"
                class="hdrtd">
              <span v-if="!isCellEdit(val,val2)">
                {{getContext(val,val2,j)}}
              </span>
              <el-input
                v-else-if="isCellDoubleSelect(i,j) && val2 === 'subjectcode'"
                type="text"
                class="cellEditClass"
                ref="gridmainEditInput"
                v-model="val[val2]"
                @keyup.enter.native="blurTextAction($event,val,val[val2])"
                @focus="focusAction"
                @blur="blurTextAction($event,val,val[val2])" />
              <el-input
                v-else-if="isCellDoubleSelect(i,j)"
                type="number"
                class="cellEditClass"
                ref="gridmainEditInput"
                v-model="val[val2]"
                @keyup.enter.native="blurAction($event,val,val[val2])"
                @focus="focusAction"
                @blur="blurAction($event,val,val[val2])" />
              <span
                v-else
                style="color: blue">
                {{getContext(val,val2,j)}}
              </span>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'bpmCGridmain',
  model: {
    prop: 'checkedList',
    event: 'checkedListChanged'
  },
  data () {
    return {
      collapse: false,
      selectedRow: -1,
      editingCell: 0,
      cacheInputValue: '',
      sumModel: []
    }
  },
  props: {
    head: {
      type: String,
      default: 'normal'
    },
    gridStatus: '',
    warnList: {
      type: Array,
      default () {
        return []
      }
    },
    gridInfo: {},
    gridTitleInfo: {},
    gridShowInfo: {},
    gridEditInfo: {},
    gridWidthInfo: {},
    gridTypeInfo: {},
    title: {
      type: String,
      default: ''
    },
    param: '',
    isCollapse: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: 200
    },
    showCheckbox: {
      type: Boolean,
      default: true
    },
    checkedList: {
      type: Array,
      default () {
        return []
      }
    }
  },
  computed: {
    gridFullWidthInfo () {
      let sum = 0
      for (let i in this.gridWidthInfo) {
        sum += parseInt(this.gridWidthInfo[i])
      }
      if (sum <= 0) {
        return []
      }
      let fullWidth = this.showCheckbox ? 940 : 980
      let resultArray = []
      for (let i in this.gridWidthInfo) {
        if (i < this.gridWidthInfo.length - 1) {
          resultArray[i] = this.gridWidthInfo[i]
        } else {
          resultArray[i] = this.gridWidthInfo[i] + fullWidth - sum
        }
      }
      return resultArray
    },
    realheight () {
      let colheight = 29 * (this.gridInfo.length + 1)
      return colheight > this.height ? colheight : this.height
    },
    sumWidth () {
      let jw = 0
      for (let aw in this.gridFullWidthInfo) {
        jw += this.gridFullWidthInfo[aw]
      }
      if (this.showCheckbox) {
        jw += 40
      }
      return jw
    },
    subModel: {
      get () {
        return this.checkedList
      },
      set (value) {
        this.$emit('checkedListChanged', value)
      }
    }
  },
  watch: {
    gridInfo (to, from) {
      if (to.length !== from.length) {
        this.selectedRow = -1
        this.sumModel = []
        this.subModel = []
      }
    },
    sumModel (to) {
      console.log('summobel', to, to.length)
      // select all...
      if (to.length >= 1) {
        let cacheModel = []
        for (let i in this.gridInfo) {
          cacheModel.push(i)
        }
        this.subModel = cacheModel
      } else {
        this.subModel = []
      }
    },
    subModel (to, from) {
      if (to.length === from.length) {
        return
      }
      if (to.length <= 0) {
        this.selectedRow = -1
      } else if (to.length === this.gridInfo.length) {
      }
    }
  },
  methods: {
    isCellEdit (val1, val2) {
      // 报销明细差旅费不可编辑
      if (this.head === 'payment' &&
        val1.subjectcode &&
        (val1.subjectcode === '500307000101' || val1.subjectcode === '500307000901')) {
        return false
      }
      for (let i in this.gridEditInfo) {
        if (this.gridEditInfo[i] + '' === val2 + '') {
          return true
        }
      }
      return false
    },
    getContext (val, val2, j) {
      let contextType = this.gridTypeInfo[j] ? this.gridTypeInfo[j] : 'text'
      let value = val[val2]
      if (contextType === 'text') {
        return value
      } else if (contextType === 'number') {
        return this.toHaveComma(value)
      } else if (contextType === 'date') {
        return this.toDate(value)
      }
      return ''
    },
    toDate (value) {
      return this.datetimeToString(value, 'yyyy-MM-dd')
    },
    pclick () {
      this.isCollapse = !this.isCollapse
      this.$emit('click', this.param)
    },
    cellSelect (i, j, val1, val2) {
      // 点击了非可编辑项处
      if (!this.isCellEdit(val1, val2)) {
        if (this.gridStatus !== 'normal') {
          return
        }
        this.editingCell = 0
        this.selectedRow = i
        return
      }
      this.$emit('cellDoubleSelect')
      if (!this.isCellDoubleSelect(i, j)) {
        this.editingCell = (i + 1) * 100 + j
        setTimeout(() => {
          this.$refs.gridmainEditInput &&
          this.$refs.gridmainEditInput[0] &&
          this.$refs.gridmainEditInput[0].focus()
        }, 100)
        return
      }
      // 点击了input对应cell
      // do nothing.
      // this.editingCell = (i + 1) * 100 + j
    },
    cellDoubleSelect (i, j, val1, val2) {
      if (this.head !== 'post' &&
        this.gridEditInfo &&
        this.gridEditInfo.length > 0) {
        return
      }
      // 点击了可编辑项处, do nothing
      if (this.isCellEdit(val1, val2)) {
        return
      }
      this.editingCell = 0
      this.selectedRow = i
      this.$emit('gridDBLClicked', i)
    },
    isCellDoubleSelect (i, j) {
      return (this.editingCell === (i + 1) * 100 + j)
    },
    className (index) {
      let classN = 'ev_light'
      if (index === this.selectedRow) {
        classN = 'selected'
      } else if (this.warnList.indexOf(index) >= 0) {
        classN = 'warned'
      } else if (index % 2 === 1) {
        classN = 'odd_light'
      }
      return classN
    },
    // 正则表达式
    validate (value) {
      let reg = /^(\+)?\d+(\.\d+)?$/
      // var reg = new RegExp(vali, 'g')
      return reg.test(value)
    },
    toHaveComma (value) {
      if (!value) {
        return '0'
      }
      // 判断是否是纯数字，如果不是不进行加点运算
      if (!this.validate(value)) { return value }
      value += ''
      var intPart = Math.floor(Number(value)) // 获取整数部分
      var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') // 将整数部分逢三一断
      var floatPart = '.00' // 预定义小数部分
      var value2Array = value.split('.')
      // =2表示数据有小数位
      if (value2Array.length === 2) {
        floatPart = value2Array[1].toString() // 拿到小数部分
        if (floatPart.length === 1) { // 补0,实际上用不着
          return intPartFormat + '.' + floatPart + '0'
        } else {
          return intPartFormat + '.' + floatPart
        }
      } else {
        return intPartFormat + floatPart
      }
    },
    focusAction (event) {
      console.log('event----->', event.currentTarget, event)
      // move the insert cursor to the end.
      this.cacheInputValue = event.currentTarget.value
      event.currentTarget.value = event.currentTarget.value
      // event.currentTarget.select()
    },
    blurAction (event, record, recordFieldValue) {
      console.log('blur.......', record, recordFieldValue, this.cacheInputValue)
      if (!this.validate(recordFieldValue)) {
        this.$notify.error(this.getResource('alert.information.srdlxbxsszlx'))
        return
      }
      this.editingCell = 0
      if (this.cacheInputValue + '' === recordFieldValue + '' ||
        parseFloat(this.cacheInputValue).toFixed(2) === parseFloat(recordFieldValue).toFixed(2)) {
        // value not changed, do nothing.
      } else {
        this.cacheInputValue = recordFieldValue
        this.$emit('gridCellEditEnd', record, recordFieldValue)
      }
    },
    blurTextAction (event, record, recordFieldValue) {
      console.log('blur text.......', record, recordFieldValue, this.cacheInputValue)
      this.editingCell = 0
      if (this.cacheInputValue + '' === recordFieldValue + '') {
        // value not changed, do nothing.
      } else {
        this.cacheInputValue = recordFieldValue
        this.$emit('gridCellEditEnd', record, recordFieldValue)
      }
    }
  }
}
</script>

<style scoped>
  .cellEditClass{
    width: 100%;
    border: 0;
    padding: 0;
    padding-right: 1px;
    margin: 0;
    font: 12px arial;
    overflow: hidden;
  }
  .header {
    position: relative;
    left: 0px;
    top: 0px;
    overflow: hidden;
    width: 100%;
  }

  .gridbox {
    overflow: hidden;
    text-align: left;
    width: 100%;
    height: 100%;
    cursor: default;
    border: 0px solid white;
  }

  .xhdr {
    background-color: #eee;
    width: 100%;
    min-height: 30px;
    overflow: hidden;
    position: relative;
  }

  .hdr {
    background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(253, 253, 253)), to(rgb(238, 240, 244)));
    display: table;
    border-collapse: separate;
    border-color: grey;
    margin-right: 20px;
    min-height: 30px;
    padding-right: 20px;
    vertical-align: middle;
    table-layout: fixed;
    width: 100%;
  }

  .hdrtr {
    display: table-row;
    vertical-align: top;
    border-color: inherit;
    border-collapse: separate;
  }

  .hdrtd {
    border-width: 1px;
    border-style: solid;
    border-collapse: separate;
    border-color: #ffffff #dfdfdf #dfdfdf #ffffff;
    cursor: default;
    display: table-cell;
    empty-cells: show;
    line-height: 16px;
    padding: 5px 0px 5px 0px;
    vertical-align: middle;
    font-size: 12px;
    text-align: center;
  }

  .hdrcell2 {
    border-width: 1px;
    border-style: solid;
    border-collapse: separate;
    border-color: #ffffff #dfdfdf #dfdfdf #ffffff;
    cursor: default;
    display: table-cell;
    empty-cells: show;
    line-height: normal;
    padding: 0px;
    vertical-align: middle;
    text-align: center;
  }

  .hdrcell {
    width: auto;
    color: rgb(96, 98, 102);
    cursor: default;
    display: block;
    empty-cells: show;
    font-family: Tahoma;
    font-size: 12px;
    font-weight: bold;
    line-height: normal;
    text-align: center;
  }

  .objbox {
    background-color: white;
    position: relative;
    width: 100%;
    overflow: auto;
  }

  .ev_light {
    border-color: #808080 #808080 #d6d6d6 #808080;
    border-collapse: separate;
    display: table-row;
    font-size: 12px;
    vertical-align: middle;
    background-color: #ffffff;
  }
  .odd_light {
    border-color: #808080 #808080 #d6d6d6 #808080;
    border-collapse: separate;
    display: table-row;
    font-size: 12px;
    vertical-align: middle;
    background-color: #f6f6f6;
  }
  .selected {
    border-color: #808080 #808080 #d6d6d6 #808080;
    border-collapse: separate;
    display: table-row;
    font-size: 12px;
    vertical-align: middle;
    background-color: #ffde99;
  }
  .warned {
    border-color: #808080 #808080 #d6d6d6 #808080;
    border-collapse: separate;
    display: table-row;
    font-size: 12px;
    vertical-align: middle;
    background-color: #fd9c9a;
  }
</style>
